//
//  JzzxVC.m
//

#import "JzzxVC.h"
#import "LocationVC.h"
#import "HistoryVC.h"

@interface JzzxVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,LocationVCDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *ivHead;
@property (weak, nonatomic) IBOutlet UILabel *labLon;
@property (weak, nonatomic) IBOutlet UILabel *labLat;
@property (weak, nonatomic) IBOutlet UILabel *labAddress;
@property (weak, nonatomic) IBOutlet UILabel *labImageUrl;
@property (weak, nonatomic) IBOutlet UITextView *tvDes;

@end

@implementation JzzxVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ivHead.layer.cornerRadius = 60.f;
    self.ivHead.layer.masksToBounds = YES;
    self.title = @"Sign In";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"History" style:UIBarButtonItemStylePlain target:self action:@selector(onHistory)];;
}

- (IBAction)onChoose:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    picker.delegate = self;
    picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:nil];
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *normalizedImage = [self normalizedImage:originalImage];
        UIImage *flippedImage = [self flipImageHorizontally:normalizedImage];
        UIImage *resizedImage = [self resizeImage:flippedImage toSize:CGSizeMake(720, 1280)];
        NSData *compressedData = [self compressImage:resizedImage maxSizeKB:200];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (compressedData) {
                [self upImageData:compressedData];
            }
        });
    });
}

- (UIImage *)normalizedImage:(UIImage *)image {
    if (image.imageOrientation == UIImageOrientationUp) return image;
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

- (UIImage *)flipImageHorizontally:(UIImage *)image {
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, image.size.width, 0);
    CGContextScaleCTM(context, -1.0, 1.0);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    UIImage *flippedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return flippedImage;
}

- (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)targetSize {
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, 1.0);
    CGRect rect = CGRectMake(0, 0, targetSize.width, targetSize.height);
    CGFloat ratio = MAX(targetSize.width / image.size.width, targetSize.height / image.size.height);
    CGSize scaledSize = CGSizeMake(image.size.width * ratio, image.size.height * ratio);
    CGRect scaledRect = CGRectMake(
        (targetSize.width - scaledSize.width) / 2.0,
        (targetSize.height - scaledSize.height) / 2.0,
        scaledSize.width,
        scaledSize.height
    );
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
    [path addClip];
    [image drawInRect:scaledRect];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resizedImage;
}

- (NSData *)compressImage:(UIImage *)image maxSizeKB:(NSInteger)maxSizeKB {
    CGFloat compression = 0.9f;
    CGFloat minCompression = 0.1f;
    NSInteger maxByte = maxSizeKB * 1024;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while (imageData.length > maxByte && compression > minCompression) {
        compression -= 0.1f;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    if (imageData.length > maxByte) {
        UIImage *tempImage = [UIImage imageWithData:imageData];
        CGFloat ratio = sqrtf((CGFloat)maxByte / (CGFloat)imageData.length);
        CGSize newSize = CGSizeMake((NSInteger)(image.size.width * ratio), (NSInteger)(image.size.height * ratio));
        tempImage = [self resizeImage:tempImage toSize:newSize];
        imageData = UIImageJPEGRepresentation(tempImage, 0.9);
    }
    return imageData.length <= maxByte ? imageData : nil;
}


- (void)upImageData:(NSData *)imageData {
    UIImage *image = [UIImage imageWithData:imageData];
    self.ivHead.image = image;
    NSString *url = @"https://www.hyjzzx.cn/api/app/video/upload?publicRead=true";
    MB_LOADING(@"Uploading...");
    [LEHttp httpUpImage:url img:image key:@"file" token:self.token response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==1){
            self.labImageUrl.text = [NSString stringWithFormat:@"%@",data[@"data"]];
        }else{
            [self showTipInfo:message okClick:nil];
        }
    }];
}


- (IBAction)onLogin:(id)sender {
    NSString *punchImg = self.labImageUrl.text;
    if(ISEmpty(punchImg)){
        return;
    }
    NSString *latitude = self.labLat.text;
    if(ISEmpty(latitude)){
        return;
    }
    
    NSString *longitude = self.labLon.text;
    if(ISEmpty(longitude)){
        return;
    }
    
    NSString *location = self.labAddress.text;
    if(ISEmpty(location)){
        return;
    }
    
    NSString *description = self.tvDes.text;
    if(ISEmpty(description)){
        return;
    }
    
    NSDate *timeDate = [NSDate now];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *punchTime = [dateFormatter stringFromDate:timeDate];
    NSDictionary *param  = @{
        @"latitude":latitude,
        @"longitude":longitude,
        @"location":location,
        @"punchImg":punchImg,
        @"punchTime":punchTime,
        @"punchType":@"1",
        @"description":description
    };
    [self.view endEditing:YES];
    MB_LOADING(@"Progressing...");
    //{"latitude":30.51617892795139,"longitude":104.0443896484375,"location":"四川省成都市双流区河池路","punchImg":"https://oss.hyjzzx.cn/public/video/2025-07-20/17529746024019786.jpg","punchTime":"2025/07/20 09:28:33","punchType":"1","description":"辅导作业，送娃上培训班"}
    NSString *url= @"https://www.hyjzzx.cn/api/app/punch/add";
    WS(weakSelf);
    NSLog(@"%@",param);
    [LEHttp httpPost:url token:self.token param:param response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==1){
            [self showTipInfo:@"Sign Success!" okClick:^{
                [weakSelf onHistory];
            }];
        }else{
            [self showTipInfo:message okClick:nil];
        }
    }];
}

- (IBAction)onAddress:(id)sender {
    LocationVC *vc = [LocationVC new];
    vc.delegate =self;
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)onLocation:(NSString *)lat lon:(NSString *)lon address:(NSString *)address{
    self.labLat.text = lat;
    self.labLon.text = lon;
    self.labAddress.text = address;
}

-(void)onHistory{
    HistoryVC *vc = [HistoryVC new];
    vc.token = self.token;
    vc.title = @"History";
    [self go2VC:vc];
}
//https://www.hyjzzx.cn/api/app/punch/list
//{"page":1,"size":30}
@end
